package middleware

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"guliedu/utils"
	"net/http"
	"strings"
	"time"
)

// jwt加密的盐
var jwtKey = []byte(utils.JwtKey)

// 需要加密的信息
type UserToken struct {
	jwt.StandardClaims
	UserName string `json:"user_name"`
}

// 获取token
func GetToken(username string) (string, int) {
	duration := time.Duration(utils.JwtExpire)
	user := UserToken{
		StandardClaims: jwt.StandardClaims{
			Issuer:    "xiaolatiao",
			ExpiresAt: time.Now().Add(duration * time.Hour).Unix(),
		},
		UserName: username,
	}

	// 生成token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, user)
	// 使用盐加密token
	tokenStr, err := token.SignedString(jwtKey)
	if err != nil {
		return "", 500
	}
	return tokenStr, 200
}

// 认证token
func AuthToken(tokenStr string) (*UserToken, int) {
	// 解析token
	token, err := jwt.ParseWithClaims(tokenStr, &UserToken{}, func(token *jwt.Token) (interface{}, error) {
		// 返回加密时用的盐
		return jwtKey, nil
	})
	if err != nil {
		return nil, 500
	}

	user, ok := token.Claims.(*UserToken)
	// 校验token
	if token.Valid && ok {
		return user, 200
	}

	return nil, 500
}

// jwt中间件
func JwtToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		//fmt.Println("=========进入了过滤器")
		tokenHeader := c.Request.Header.Get("Authorization")
		if tokenHeader == "" {
			c.JSON(http.StatusOK, gin.H{
				"code":    500,
				"message": "请求失败！",
			})
			c.Abort()
			return
		}
		checkToken := strings.Split(tokenHeader, " ")
		if len(checkToken) == 0 {
			c.JSON(http.StatusOK, gin.H{
				"code":    500,
				"message": "请求失败！",
			})
			c.Abort()
			return
		}

		if len(checkToken) != 2 && checkToken[0] != "Bearer" {
			c.JSON(http.StatusOK, gin.H{
				"code":    500,
				"message": "请求失败！",
			})
			c.Abort()
			return
		}
		_, tCode := AuthToken(checkToken[1])
		if tCode != 200 {
			c.JSON(http.StatusOK, gin.H{
				"code":    500,
				"message": "请求失败！",
			})
			c.Abort()
			return
		}
		c.Next()
	}
}
